﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Com.ThrongIn.BLL;
using Com.ThrongIn.BE;
using System.Web.Services;
namespace ThrongIn
{
    /// <summary>
    /// Summary description for UserHandler
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class UserHandler : IHttpHandler,System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            string fn = context.Request.Form[0];
            var json = new System.Web.Script.Serialization.JavaScriptSerializer();
            User user = json.Deserialize<User>(fn);
            if (user.Email.Equals("TimeOut", StringComparison.CurrentCultureIgnoreCase))
                ClearSession();
            else
                AddUser(user);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private  void AddUser(User user)
        {
            if (HttpContext.Current.Session["USER"] == null || ((User)HttpContext.Current.Session["USER"]).Email.Equals(user.Email) == false)
            {
                Int64 id = new UserBLL().AddUser(user);
                user.Id = id;
                HttpContext.Current.Session["USER"] = user;
            }
        }

        private void ClearSession()
        {
            HttpContext.Current.Session.Clear();
            HttpContext.Current.Session.Abandon();
        }
    }
}